import java.util.concurrent.Semaphore;

public class Demo03 {
    private static Semaphore sem1 = new Semaphore(1);
    private static Semaphore sem2 = new Semaphore(0);
    private static Semaphore sem3 = new Semaphore(0);

    private static final int end = 100;
    private static volatile int count = 0;

    public static class Print implements Runnable {
        private int id;
        private Semaphore currentSem;
        private Semaphore nextSem;

        public Print(int id, Semaphore currentSem, Semaphore nextSem) {
            this.id = id;
            this.currentSem = currentSem;
            this.nextSem = nextSem;
        }

        @Override
        public void run() {
            while (count <= end) {
                try {
                    //获得信号量
                    currentSem.acquire();
                    if (count <= end) {
                        System.out.println("Thread " + id + ": " + count++);
                    }
                    //释放信号量
                    nextSem.release();
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
            }
        }
    }

    public static void main(String[] args) {
        //设置当前线程的信号量是sem1，下一个是sem2
        Thread t1 = new Thread(new Print(1, sem1, sem2));
        Thread t2 = new Thread(new Print(2, sem2, sem3));
        Thread t3 = new Thread(new Print(3, sem3, sem1));

        t1.start();
        t2.start();
        t3.start();

        // Release the first semaphore to start the first thread
        sem1.release();
    }
}
